package io.github.idol.roomlist.room

import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.MutableLiveData
import android.util.Log
import android.util.MutableDouble
import com.google.gson.Gson
import io.github.idol.data.ApiRepository
import io.github.idol.data.ExtInfo
import io.github.idol.utils.RxJavaUtils

/**
 * Created by codeczx on 2018/8/8 下午 09:10.
 * Class description:
 */

class RoomDetailViewModel(
        application: Application,
        private val apiRepository: ApiRepository
) :AndroidViewModel(application){

    var lastTime = 0L
    var roomId =0

    private val roomDetailData = MutableLiveData<List<ExtInfo>>()

    fun getRoomDetail(){
        apiRepository.getRoomDetail(roomId,lastTime)
                .compose(RxJavaUtils.flowableAppleNetworkSchedulers())
                .subscribe({
                    var list= ArrayList<ExtInfo>()
                    it.content?.data?.forEach {
                        val extInfo = Gson().fromJson(it.extInfo,ExtInfo::class.java)
                        extInfo.senderAvatar = "https://source.48.cn"+extInfo.senderAvatar
                        extInfo.msgTime = it.msgTime
                        extInfo.bodys = it.bodys
                        Log.i("TAG",extInfo.senderAvatar)
                        list.add(extInfo)
                    }
                    list.sortBy { it.msgTime }
                    list.addAll(roomDetailData.value.orEmpty())
                    roomDetailData.value = list
                    lastTime = list.get(0).msgTime
                },Throwable::printStackTrace)
    }

    fun getRoomDetailData():MutableLiveData<List<ExtInfo>>{
        return roomDetailData
    }
}